package strengthen.spatial.impl;

import java.awt.image.Raster;
import java.util.Arrays;

import strengthen.spatial.AbstractFilterMask;

public class MedianFilterMask extends AbstractFilterMask {

	public MedianFilterMask(int size) {
		super(size);
	}

	@Override
	public int[] calculatePixel(int[] pixel, int x, int y, Raster raster) {
		calculateMaskActualSize(x, y, raster);

		int[] px = new int[raster.getNumBands() * maskRect.width
				* maskRect.height];
		raster.getPixels(maskRect.x, maskRect.y, maskRect.width,
				maskRect.height, px);

		int[] simple = new int[maskRect.width * maskRect.height];
		for (int i = 0; i < raster.getNumBands(); i++) {
			extractArray(simple, px, i, raster.getNumBands());
			Arrays.sort(simple);
			pixel[i] = simple[(int) Math.ceil(simple.length / 2.0)];
		}

		return pixel;
	}

	private void extractArray(int[] dest, int[] source, int index, int bands) {
		int di = 0;
		for (int i = index; i < source.length; i = i + bands) {
			dest[di++] = source[i];
		}
	}

}
